"""
主应用入口
"""
import asyncio
import signal
import sys
from fastapi import FastAPI
from contextlib import asynccontextmanager

from config.settings import settings
from utils.logger import audit_logger
from database import test_connection, init_database
from services.redis_client import redis_client
from workers.audit_worker import audit_worker
from core.audit_engine import audit_engine
from monitoring.metrics import metrics_collector


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    audit_logger.info("内容审核服务启动中...")
    
    # 测试数据库连接
    if not test_connection():
        audit_logger.warning("数据库连接失败，但继续启动服务（某些功能可能不可用）")
        sys.exit(1)  # 临时注释掉，允许服务启动
    
    # 初始化数据库
    try:
        init_database()
    except Exception as e:
        audit_logger.error(f"数据库初始化失败: {e}")
        sys.exit(1)
    
    # 测试Redis连接
    if not redis_client.health_check():
        audit_logger.error("Redis连接失败，服务启动中止")
        sys.exit(1)

    # 启动审核工作进程
    audit_worker.start()

    audit_logger.info("内容审核服务启动成功")

    yield

    # 关闭时执行
    audit_logger.info("内容审核服务正在关闭...")
    audit_worker.stop()


# 创建FastAPI应用
app = FastAPI(
    title="内容审核算法服务",
    description="基于机器学习的内容审核系统",
    version="1.0.0",
    lifespan=lifespan
)


@app.get("/")
async def root():
    """根路径"""
    return {"message": "内容审核算法服务运行中", "version": "1.0.0"}


@app.get("/health")
async def health_check():
    """健康检查"""
    db_status = test_connection()
    redis_status = redis_client.health_check()
    worker_status = audit_worker.get_status()

    return {
        "status": "healthy" if db_status and redis_status and worker_status['is_running'] else "unhealthy",
        "database": "connected" if db_status else "disconnected",
        "redis": "connected" if redis_status else "disconnected",
        "worker": worker_status,
        "queue_length": redis_client.get_queue_length(settings.audit_queue_name)
    }


@app.get("/statistics")
async def get_statistics():
    """获取审核统计信息"""
    worker_status = audit_worker.get_status()
    engine_stats = audit_engine.get_audit_statistics()

    return {
        "worker_status": worker_status,
        "engine_statistics": engine_stats,
        "queue_info": {
            "audit_queue": redis_client.get_queue_length(settings.audit_queue_name),
            "result_queue": redis_client.get_queue_length(settings.result_queue_name)
        }
    }


@app.post("/worker/reset")
async def reset_worker_statistics():
    """重置工作进程统计"""
    audit_worker.reset_statistics()
    return {"message": "工作进程统计已重置"}


@app.get("/metrics")
async def get_metrics():
    """获取Prometheus格式的监控指标"""
    from fastapi import Response
    metrics_data = metrics_collector.get_metrics()
    return Response(content=metrics_data, media_type="text/plain")


@app.get("/metrics/summary")
async def get_metrics_summary():
    """获取指标摘要"""
    return metrics_collector.get_summary()


def signal_handler(signum, frame):
    """信号处理器"""
    audit_logger.info(f"接收到信号 {signum}，正在关闭服务...")
    sys.exit(0)


if __name__ == "__main__":
    import uvicorn
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 启动服务
    uvicorn.run(
        "main:app",
        host=settings.api_host,
        port=settings.api_port,
        workers=1,  # 开发环境使用单进程
        reload=True,  # 开发环境启用热重载
        log_level=settings.log_level.lower()
    )
